/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.fzhucc.modules.appletBanner.service;

import cn.hutool.core.io.resource.FileObjectResource;
import com.fzhucc.exception.BadRequestException;
import com.fzhucc.modules.activity.domain.Activity;
import com.fzhucc.modules.activity.domain.dto.ActivityQueryCriteria;
import com.fzhucc.modules.activity.repository.ActivityRepository;
import com.fzhucc.modules.appletBanner.domain.AppletBanner;
import com.fzhucc.modules.appletBanner.domain.dto.AppletBannerAddDto;
import com.fzhucc.modules.appletBanner.domain.dto.AppletBannerDto;
import com.fzhucc.modules.appletBanner.domain.dto.AppletBannerQueryCriteria;
import com.fzhucc.modules.appletBanner.domain.dto.AppletBannerSkipResp;
import com.fzhucc.modules.appletBanner.repository.AppletBannerRepository;
import com.fzhucc.modules.appletBanner.service.mapstruct.AppletBannerMapper;
import com.fzhucc.modules.notice.domain.Notice;
import com.fzhucc.modules.notice.repository.NoticeRepository;
import com.fzhucc.modules.pms.domain.Project;
import com.fzhucc.modules.pms.repository.ProjectRepository;
import com.fzhucc.modules.system.domain.User;
import com.fzhucc.modules.system.repository.UserRepository;
import com.fzhucc.modules.system.service.dto.UserQueryCriteria;
import com.fzhucc.utils.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.*;

import static com.fzhucc.modules.appletBanner.domain.AppletBanner.*;

/**
 * @author yyg
 * @website https://eladmin.vip
 * @description 服务实现
 * @date 2022-11-25
 **/
@Service
@RequiredArgsConstructor
public class AppletBannerService {

    private final AppletBannerRepository appletBannerRepository;

    private final NoticeRepository noticeRepository;

    private final ProjectRepository projectRepository;

    private final ActivityRepository activityRepository;
    private final AppletBannerMapper appletBannerMapper;

    private final UserRepository userRepository;

    @Value("${org.area.all}")
    public String all;

    @Value("${org.area.all2}")
    public String all2;

    @Value("${org.area.fz}")
    public String fz;

    @Value("${org.area.fz2}")
    public String fz2;

    public Map<String, Object> queryAll(AppletBannerQueryCriteria criteria, Pageable pageable) {
        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.setOrgArea(null);
            }
        } else {
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        Page<AppletBanner> page = appletBannerRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<AppletBannerDto> map = page.map(appletBannerMapper::toDto);
        List<AppletBannerDto> list = map.getContent();
        if (list != null) {
            for (AppletBannerDto appletBannerDto : list) {
                String skipType = appletBannerDto.getSkipType();
                if (skipType.equals(SKIP_NOTICE_TYPE)) {
                    Optional<Notice> notice = noticeRepository.findById(Integer.parseInt(appletBannerDto.getSkipId()));
                    if (notice.isPresent()) {
                        AppletBannerSkipResp appletBannerSkipResp = new AppletBannerSkipResp();
                        appletBannerSkipResp.setSkipId(appletBannerDto.getSkipId());
                        appletBannerSkipResp.setName(notice.get().getTitle());
                        appletBannerSkipResp.setNoticeType(notice.get().getType());
                        appletBannerSkipResp.setNoticeUrl(notice.get().getContentUrl());
                        appletBannerDto.setSkipInfo(appletBannerSkipResp);
                    }
                }
                if (skipType.equals(SKIP_ACTIVITY_TYPE)) {
                    Optional<Activity> activity = activityRepository.findById(Integer.parseInt(appletBannerDto.getSkipId()));
                    if (activity.isPresent()) {
                        AppletBannerSkipResp appletBannerSkipResp = new AppletBannerSkipResp();
                        appletBannerSkipResp.setSkipId(appletBannerDto.getSkipId());
                        appletBannerSkipResp.setName(activity.get().getTitle());
                        appletBannerDto.setSkipInfo(appletBannerSkipResp);
                    }
                }
                if (skipType.equals(SKIP_PROJECT_TYPE)) {
                    Optional<Project> project = projectRepository.findById(appletBannerDto.getSkipId());
                    if (project.isPresent()) {
                        AppletBannerSkipResp appletBannerSkipResp = new AppletBannerSkipResp();
                        appletBannerSkipResp.setSkipId(appletBannerDto.getSkipId());
                        appletBannerSkipResp.setName(project.get().getProjectName());
                        appletBannerDto.setSkipInfo(appletBannerSkipResp);
                    }
                }
            }
        }
        return PageUtil.toPage(map);
    }


    public Map<String, Object> showIndex(AppletBannerQueryCriteria criteria, Pageable pageable) {
        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                //criteria.setOrgArea(null);
            }
        } else {
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }

        Page<AppletBanner> page = appletBannerRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Page<AppletBannerDto> map = page.map(appletBannerMapper::toDto);
        List<AppletBannerDto> list = map.getContent();
        if (list != null) {
            for (AppletBannerDto appletBannerDto : list) {
                String skipType = appletBannerDto.getSkipType();
                if (skipType.equals(SKIP_NOTICE_TYPE)) {
                    Optional<Notice> notice = noticeRepository.findById(Integer.parseInt(appletBannerDto.getSkipId()));
                    if (notice.isPresent()) {
                        AppletBannerSkipResp appletBannerSkipResp = new AppletBannerSkipResp();
                        appletBannerSkipResp.setSkipId(appletBannerDto.getSkipId());
                        appletBannerSkipResp.setName(notice.get().getTitle());
                        appletBannerSkipResp.setNoticeType(notice.get().getType());
                        appletBannerSkipResp.setNoticeUrl(notice.get().getContentUrl());
                        appletBannerDto.setSkipInfo(appletBannerSkipResp);
                    }
                }
                if (skipType.equals(SKIP_ACTIVITY_TYPE)) {
                    Optional<Activity> activity = activityRepository.findById(Integer.parseInt(appletBannerDto.getSkipId()));
                    if (activity.isPresent()) {
                        AppletBannerSkipResp appletBannerSkipResp = new AppletBannerSkipResp();
                        appletBannerSkipResp.setSkipId(appletBannerDto.getSkipId());
                        appletBannerSkipResp.setName(activity.get().getTitle());
                        appletBannerDto.setSkipInfo(appletBannerSkipResp);
                    }
                }
                if (skipType.equals(SKIP_PROJECT_TYPE)) {
                    Optional<Project> project = projectRepository.findById(appletBannerDto.getSkipId());
                    if (project.isPresent()) {
                        AppletBannerSkipResp appletBannerSkipResp = new AppletBannerSkipResp();
                        appletBannerSkipResp.setSkipId(appletBannerDto.getSkipId());
                        appletBannerSkipResp.setName(project.get().getProjectName());
                        appletBannerDto.setSkipInfo(appletBannerSkipResp);
                    }
                }
            }
        }
        return PageUtil.toPage(map);
    }

    //根据不同设置不同的部门查看 处理  福建省;  或者  福建省;福州市;   或者 福建省;福州市;马尾区; 这种类型
    public String setCriteria(AppletBannerQueryCriteria criteria) {
        Long userId = null;
        try {
            userId = SecurityUtils.getCurrentUserId();
        } catch (Exception e) {
            String orgArea = criteria.getOrgArea();
            if (orgArea != null && orgArea.equals(all)) { //如果等于福建省则查全部
                return null;
            } else {
                return orgArea;
            }
        }
        if (userId != null) {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() != null && (res.getOrgArea().equals(all) || res.getOrgArea().equals(all2))) {//包含福建省 则查全部
                return null;
            } else {
                if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                    //不赋予则返回所有都能看
                    return null;
                }
                if (res.getOrgArea().contains(";")) {
                    String[] split = res.getOrgArea().split(";");
                    if (split.length == 2) {
                        return split[1];
                    } else if (split.length == 3) {
                        return split[2];
                    } else if (split.length == 1) {
                        return split[0];
                    } else {
                        throw new BadRequestException("未符合规范的地区区域");
                    }
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            }
        } else {
            throw new BadRequestException("用户ID未找到");
        }
    }

    public String orgAreaReturn() {
        Long userId = SecurityUtils.getCurrentUserId();
        if (userId == null) {//未登录则外面传进来
            return "";
        } else {
            Optional<User> userOptional = userRepository.findById(userId);
            User res = userOptional.get();
            if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                //不赋予则返回所有都能看
                return null;
            }
            if (res.getOrgArea().contains(";")) {
                String[] split = res.getOrgArea().split(";");
                if (split.length == 2) {
                    return split[1];
                } else if (split.length == 3) {
                    return split[1];
                } else if (split.length == 1) {
                    return split[0];
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            } else {
                throw new BadRequestException("未符合规范的地区区域");
            }
        }
    }


    public String orgAreaReturnIfHave(String org) {
        if (org != null && !org.equals("")) {
            return org;
        } else {
            Long userId = SecurityUtils.getCurrentUserId();
            if (userId == null) {//未登录则外面传进来
                return "";
            } else {
                Optional<User> userOptional = userRepository.findById(userId);
                User res = userOptional.get();
                if (res.getOrgArea() == null || res.getOrgArea().equals("")) {
                    //不赋予则返回所有都能看
                    return null;
                }
                if (res.getOrgArea().contains(";")) {
                    String[] split = res.getOrgArea().split(";");
                    if (split.length == 2) {
                        return split[1];
                    } else if (split.length == 3) {
                        return split[1];
                    } else if (split.length == 1) {
                        return split[0];
                    } else {
                        throw new BadRequestException("未符合规范的地区区域");
                    }
                } else {
                    throw new BadRequestException("未符合规范的地区区域");
                }
            }
        }
    }

    public List<AppletBannerDto> queryAll(AppletBannerQueryCriteria criteria) {
        if (criteria.getOrgArea() != null && !criteria.getOrgArea().equals("")) {
            //h5的直接传orgArea
            if (criteria.getOrgArea().equals(all)) {
                criteria.setOrgArea(null);
            }
        } else {
            //管理端根据登录用户地区
            criteria.setOrgArea(setCriteria(criteria));
        }
        return appletBannerMapper.toDto(appletBannerRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    public AppletBannerDto findById(Integer id) {
        AppletBanner appletBanner = appletBannerRepository.findById(id).orElseGet(AppletBanner::new);
        ValidationUtil.isNull(appletBanner.getId(), "AppletBanner", "id", id);
        return appletBannerMapper.toDto(appletBanner);
    }

    @Transactional(rollbackFor = Exception.class)
    public AppletBannerDto create(AppletBannerAddDto appletBannerAddDto) {
        AppletBanner resources = new AppletBanner();
        resources.setImg(appletBannerAddDto.getImg());
        resources.setName(appletBannerAddDto.getName());
        resources.setIsShow(appletBannerAddDto.getIsShow());
        resources.setSort(appletBannerAddDto.getSort());
        resources.setUrl(appletBannerAddDto.getUrl());
        resources.setType(appletBannerAddDto.getType());
        //resources.setOrgArea(orgAreaReturn());
        resources.setOrgArea(orgAreaReturnIfHave(appletBannerAddDto.getOrgArea()));
        resources.setText(appletBannerAddDto.getText());
        String skipType = appletBannerAddDto.getSkipType();
        if (skipType.equals(SKIP_NOT_HAVE_TYPE)) {
            resources.setSkipId(null);
            resources.setSkipType(SKIP_NOT_HAVE_TYPE);
            resources.setContext(null);
        } else if (skipType.equals(SKIP_NOTICE_TYPE)) {
            try {
                String skipId = appletBannerAddDto.getSkipId();
                int res = Integer.parseInt(skipId);
                Optional<Notice> noticeRes = noticeRepository.findById(res);
                if (!noticeRes.isPresent()) {
                    throw new BadRequestException("关联通知未找到");
                }
                resources.setSkipId(appletBannerAddDto.getSkipId());
                resources.setSkipType(SKIP_NOTICE_TYPE);
                resources.setContext(null);
            } catch (NumberFormatException e) {
                throw new BadRequestException("关联通知id未找到");
            }
        } else if (skipType.equals(SKIP_ACTIVITY_TYPE)) {
            try {
                String skipId = appletBannerAddDto.getSkipId();
                int res = Integer.parseInt(skipId);
                Optional<Activity> ActivityRes = activityRepository.findById(res);
                if (!ActivityRes.isPresent()) {
                    throw new BadRequestException("关联活动未找到");
                }
                resources.setSkipId(appletBannerAddDto.getSkipId());
                resources.setSkipType(SKIP_ACTIVITY_TYPE);
                resources.setContext(null);
            } catch (NumberFormatException e) {
                throw new BadRequestException("关联活动id未找到");
            }
        } else if (skipType.equals(SKIP_PROJECT_TYPE)) {
            String skipId = appletBannerAddDto.getSkipId();
            Optional<Project> res = projectRepository.findById(skipId);
            if (!res.isPresent()) {
                throw new BadRequestException("关联项目未找到");
            }
            resources.setSkipId(appletBannerAddDto.getSkipId());
            resources.setSkipType(SKIP_PROJECT_TYPE);
            resources.setContext(null);
        } else if (skipType.equals(SKIP_URL_TYPE)) {//喜报
            resources.setSkipId(null);
            resources.setSkipType(SKIP_URL_TYPE);
            resources.setContext(appletBannerAddDto.getContext());
        } else if (skipType.equals(SKIP_RICH_TEXT_TYPE)) { //喜报
            resources.setSkipId(null);
            resources.setSkipType(SKIP_RICH_TEXT_TYPE);
            resources.setContext(appletBannerAddDto.getContext());
        } else {
            throw new BadRequestException("请选择正确的关联类型");
        }
        return appletBannerMapper.toDto(appletBannerRepository.save(resources));
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(AppletBanner resources) {
        AppletBanner appletBanner = appletBannerRepository.findById(resources.getId()).orElseGet(AppletBanner::new);
        ValidationUtil.isNull(appletBanner.getId(), "AppletBanner", "id", resources.getId());
        appletBanner.copy(resources);
        //appletBanner.setOrgArea(orgAreaReturn());
        appletBanner.setOrgArea(orgAreaReturnIfHave(resources.getOrgArea()));
        appletBannerRepository.save(appletBanner);
    }

    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            appletBannerRepository.deleteById(id);
        }
    }

    public void download(List<AppletBannerDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (AppletBannerDto appletBanner : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("图片地址", appletBanner.getImg());
            map.put("名称", appletBanner.getName());
            map.put("排序", appletBanner.getSort());
            map.put("是否小程序展示", appletBanner.getIsShow());
            map.put("类型", appletBanner.getType());
            map.put("通知", appletBanner.getText());
            map.put("跳转关联的id", appletBanner.getSkipId());
            map.put("跳转关联类型用来区别跳转到哪个分类", appletBanner.getSkipType());
            map.put("地区划分", appletBanner.getOrgArea());
            map.put("地址", appletBanner.getUrl());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}